package app

import (
	"gitee.com/dn-jinmin/video_state/core"
	"github.com/gin-gonic/gin"
	"net/http"
	"strings"
)

type Option struct {
	Address string
}

type app struct {
	address string

}

func NewApp(option Option) *app {
	return &app{
		address: option.Address,
	}
}

func (a *app) Run() {
	r := gin.Default()

	r.StaticFS("view", http.Dir("./view"))
	r.GET("/", Index)
	r.POST("/video_state", VideoState)

	r.Run(a.address)
}

func Index(ctx *gin.Context)  {
	ctx.File("view/index.html")
}

func VideoState(c *gin.Context)  {
	type Data struct {
		Path string `json:"path"`
		Where string `json:"where"`
		Group string `json:"group"`
		SuffixType string `json:"suffix_type"`
	}

	var d Data

	if err := c.ShouldBindJSON(&d); err != nil {
		c.JSON(200, gin.H{
			"code":501,
			"msg":"数据问题" + err.Error(),
		})
		return
	}

	var (
		rets []*core.FileVideos
		err error
	)

	state := core.NewState(core.Option{
		FilePath: d.Path,
		Where:    d.Where,
		SuffixType: d.SuffixType,
	})

	if d.Group == "" {
		rets, err = state.FilePathState()
	} else {
		gs := strings.Split(d.Group, ",")
		rets, err = state.Groups(gs)
	}

	if err != nil {
		c.JSON(200, gin.H{
			"code":502,
			"msg":err.Error(),
		})
		return
	}
	c.JSON(200, gin.H{
		"code":200,
		"data":rets,
	})
	return

}